/**
 * @author Fei Chen
 * Latest update: 
 */
 
(function() {
  var geostack = [];
  var totalPage = 0;
  var searchNews = null;
  var searchWe = null;
  var searchStack = [];
  var searchResult = [];
  var keyword = "春运";
  var regions = [];
  
  var citiescn = [
    ['安'], //a
    ['北','白','宝'], //b
    ['长','常','池','潮','重','成','慈','从'], //c
    ['大','丹','东','达'], //d
    [], //e
    ['福','佛','富','奉','阜'], //f
    ['贵','公','巩','固','广','高','桂','个','甘'], //g
    ['合','海','淮','黄','河','哈','杭','呼','桦','湖','衡','惠','黑','汉','潢'], //h
    [], //i
    ['济','蛟','金','江','靖','姜','建','晋','吉','集','句','嘉','揭','景'], //j
    ['昆','开'], //k
    ['连','临','洛','灵','兰','拉','溧','丽','六','辽','柳'], //l
    ['绵','眉','茂', '麻'], //m
    ['南','宁','内'], //n
    [], //o
    ['浦','普','邳','平','莆'], //p
    ['秦','启','泉','青','钦','衢','齐'], //q
    ['如','瑞'], //r
    ['舒','绍','上','宿','商','韶','石','沈','四','双','松','苏','深','汕','陕','山','十'], //s
    ['天','太','通','泰','桐','台'], //t
    [], //u
    [], //v
    ['武','乌','无','温','芜','吴','渭'], //w
    ['西','新','湘','徐','兴','厦','襄','咸'], //x
    ['榆','宜','盐','仪','余','乐','义','永','烟','银','延','扬','阳','玉','云'], //y
    ['漳','淄','增','珠','湛','肇','郑','张','镇','诸','舟','中','浙'] //z
  ];
  var letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  function getCapital(city){
    for(var i = 0; i < citiescn.length; i++) {
      for(var j = 0; j < citiescn[i].length; j++) {
        if(city.charCodeAt(0) == citiescn[i][j].charCodeAt(0)) {
          return letter[i];
        }
      }
    }
    return null;
  }

  function $(id) {
    return document.getElementById(id);
  }
  function $$(name){
   return document.getElementsByTagName(name);
  }
  function $n(tag, className, prt, attributes){
    var el = document.createElement(tag);
    el.className = className || "";
    if (prt) prt.appendChild(el);
    if (attributes){
      for (var nm in attributes){
        el.setAttribute(nm, attributes[nm])
      }
    }
    return el;
  }
  
  function parsePX(pxstr) {
    return parseInt(pxstr.substr(0, pxstr.length - 2));
  }
 
  function $h(url){
    var head = $$("head")[0] || $n("head", document.body.parentNode);
    $n("script", null, head, { "src": url });
  }
  function autoScroll(node){
    var parent = node.parentNode.parentNode;
    var offset = node.offsetHeight;
    var parentTop = parent.scrollTop;
    var nodeTop = node.offsetTop - node.parentNode.offsetTop;
    var curOffset = nodeTop - parentTop;
    if (curOffset > parent.offsetHeight) {  //scroll bar down
      parent.scrollTop = parent.scrollTop + (curOffset - parent.clientHeight + offset);
    } else if (curOffset < 0) {  //scroll bar up
      parent.scrollTop = parent.scrollTop - Math.abs(curOffset);
    }
  }
  
  
  
  function _un(str){
    return str.replace(/&([^;]+);/g, function(s, entity){
      switch (entity) {
        case 'amp':
          return '&';
        case 'lt':
          return '<';
        case 'gt':
          return '>';
        case 'quot':
          return '"';
        default:
          if (entity.charAt(0) == '#') {
            var n = Number('0' + entity.substr(1));
            if (!isNaN(n)) {
              return String.fromCharCode(n);
            }
          }
          return s;
      }
    });
  };
  
  function makeShareButton(){
    if (!google || !google.share || !google.share.SharingWidget) {
      GLog.write("failure");
      return;
    }
    // TODO: refine the text here !!!!
    var g = {
      'linkText': '将此地图分享给朋友',
      'url': 'http://ditu.google.cn/maps/mpl?moduleurl=http://dituapps.appspot.com/html/chunyun.xml',
      'title': '地图--春运信息快速查询',
      'image': 'http://ditu.google.cn/intl/zh-CN_cn/images/maps_logo_beta_small.png',
      'subject_template': _un('{FROM}邀请您一起去谷歌地图看看春运信息'),
      'comments_template': _un('春运信息好分散啊？不用费心了，您的朋友（{FROM}）在谷歌地图上已经找到了一个搜集很详细的地方，来看看吧 :) '),
      'description': '春运信息好分散啊？不用费心了，我们已经在地图上都给你找出来了，快来看看吧。',
      'buttonStyle': 'link',
      'tabs': 'email,email',
      'popup': true,
      'nopreview': true,
      'noaddto': true,
      'noThumbnail': true
    };
    new google.share.SharingWidget("share_button", g);
    var link = $n("a", "share-link", $("share_button"), {href:"http://ditu.google.com/maps/mpl?moduleurl=http://dituapps.appspot.com/html/chunyun.xml", target:"_blank"});
    link.innerHTML = "保存此地图到“我的地图”";
  };
  
  var rpcProxy = (function(){
    // Private member
    var backend_url = "http://" + window.location.host + "/chunyun";

    var msgBoard = $("listContainer");
    var msgFlag = 0;
    var msgCounter = 0;
    var msgTimeId = null;
    function getParamStr(paramObj){
      var paramArray = [];
      for (var i in paramObj) {
        if (i != "toJSONString" && paramObj[i] != null) {
          var paramToken = i + '=' + paramObj[i];
          paramArray.push(paramToken);
        }
      }
      return paramArray.join("&");
    }
    function request(param, callBackName){
      var paramStr = getParamStr(param);
      var url = backend_url + "?" + paramStr + "&random=" + Math.random();
      url += '&callback=' + callBackName;
      var api = param['api'];
      var scriptTag = document.createElement('script');
      scriptTag.setAttribute('type', 'text/javascript');
      scriptTag.setAttribute('charset', 'utf-8');
      scriptTag.setAttribute('id', 'jsonpScriptTag' + api);
      scriptTag.setAttribute('src', url);
      var oldTag = document.getElementById('jsonpScriptTag' + api);
      var head = document.getElementsByTagName('head')[0];
      if (oldTag) {
        head.removeChild(oldTag);
      }
      head.appendChild(scriptTag);
//       var api = param.api;
//       $h(api+"Sample.js");
//       GLog.write(url);
    }
    function openMsgBoard(msg){
      msg = "<div style='text-align:center;padding:10px;font-size:15px;font-weight:bold;height:100px;line-height:100px;color:red;'>数据加载中...</div>";
      msgBoard.innerHTML = msg;    }
    
    function closeMsgBoard(){
      
    }
    
    return { // Public members
      getOptions: function(){
        openMsgBoard("数据加载中...");
        var param = {
          api: 'options'
        }
        request(param, 'ChunyunMap.callback_options');
      },
      getWeather: function(page, region){
        if(!page) {
          page = 0;
        }
        openMsgBoard("数据加载中...");
        var param = {
          api: 'weather',
          page: page,
          region: region
        }
        request(param, 'ChunyunMap.callback_weather');
      },
      getSearch:function(regionId, categoryId, date, pageNo){
        $("listContainer").innerHTML = "";
        openMsgBoard("数据加载中...");
        
        if(regionId == null && date == null) {
          var dateTen = new Date();
          var dy = dateTen.getDate();
          dy -= 10;
          dateTen.setDate(dy);
          var mn = dateTen.getMonth() + 1;
          if(mn < 10) {
            mn = "0" + mn;
                      }
          
          if(dy < 10) {
            dy = "0" + dy;
                       }
          dateTen = "" + dateTen.getFullYear() + mn + dy;
              
          param = {
            api: 'search',
            region: regionId,
            date: dateTen,
            category: categoryId,
            page: pageNo,
            inc: 1
                       }
                  }
        else {
          param = {
            api: 'search',
            region : regionId,
            date : date,
            category : categoryId,
            page : pageNo
                      }
          if($("viewafter").checked) {
            param["inc"] = 1;
                       }
                  }
        request(param, 'ChunyunMap.callback_search');
      },
      getSearchAll:function(key, page){
        openMsgBoard("数据加载中...");
        var param = {
          api: 'searchAll',
          key : key,
          page : page
        }
        request(param, 'ChunyunMap.callback_search');
      },
      setWGeo: function(name, latlng){
        var param = {
          api: 'wgeocode',
          name: name,
          latlng: latlng
        };
        request(param, "abc");
      },
      setGeo: function(name, latlng){
        var param = {
          api: 'geocode',
          name: name,
          latlng: latlng
        };
        request(param, "abc");
      },
      getOptionsCallback: function(options){
        mgr.initOptions(options);
        closeMsgBoard();
      },
      getSearchCallback : function(result){
        mgr.importResult(result);
        closeMsgBoard();
      },
      getWeatherCallback: function(result){
        mgr.importWeather(result);
        closeMsgBoard();
      }
    }
  })();
  
  
  var mgr = (function(){
    var map = null;
    var geocoder = new GClientGeocoder();
    var dom = {
      region : $("region"),
      category : $("category"),
      date : $("date"),
      container : $("listContainer"),
      page : $("pageList")
    }
    var cur = {
      region : null,
      category : null,
      date : null,
      page : null
    };
    var cached = {
      region : null,
      category : null,
      latlng: {},
      points : []
    }
    function resizeMap(){
      var bounds = new GLatLngBounds();
      for(var i = 0, point; point = cached.points[i]; i++){
        bounds.extend(point);
      }
      var level = map.getBoundsZoomLevel(bounds);
      if(level > 10) {
        level = 10;
      }
      map.setCenter(bounds.getCenter(), level);
    }
    
    function addNode(pos){
      var node = $n("p", "list-entry", dom.container);
      node.innerHTML = pos["label"];
      return node;
    }

    function addWNode(title, icon){
      var node = $n("p", "list-entry", dom.container);
      node.innerHTML = '<img style="vertical-align:middle;margin-right:5px;" src="' + icon + '"></img>' + title;
      return node;
    }

    function addWMarker(pos,iconurl){
      var icon = new GIcon();
      icon.image = iconurl;
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 32);
      icon.infoWindowAnchor = new GPoint(16, 2);
      var marker = new GMarker(pos, {icon:icon});
      map.addOverlay(marker);
      cached.points.push(pos);
      return marker;
    }


    function addWListener(marker, node){
      GEvent.addListener(marker, "click", GEvent.callbackArgs(this, openWInfoWindow, node.city));
      GEvent.addListener(marker, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node));
      GEvent.addListener(marker, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node));
      GEvent.addDomListener(node, "click", GEvent.callbackArgs(this, openWInfoWindow, node.city));
      GEvent.addDomListener(node, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node));
      GEvent.addDomListener(node, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node));
    }
    function addMarker(pos, iconurl){
      var icon = new GIcon();
      icon.image = iconurl;
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 16);
      icon.infoWindowAnchor = new GPoint(12, 16);
      var point = new GLatLng(parseFloat(pos.latlng[0]), parseFloat(pos.latlng[1]));
      var marker = new GMarker(point, { title:pos["label"], icon: icon});
      marker.point = point;
      map.addOverlay(marker);
      cached.points.push(point);
      return marker;
    }
    function addListener(node, marker){
      var pos = node.pos;
      GEvent.addListener(marker, "click", GEvent.callbackArgs(this, openInfoWindow, marker, pos));
      GEvent.addListener(marker, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node, pos));
      GEvent.addListener(marker, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node, pos));
      GEvent.addDomListener(node, "click", GEvent.callbackArgs(this, openInfoWindow, marker, pos));
      GEvent.addDomListener(node, "mouseover", GEvent.callbackArgs(this,highlightPos, marker, node, pos));
      GEvent.addDomListener(node, "mouseout", GEvent.callbackArgs(this,unhighlightPos, marker, node, pos));
    }
    function highlightPos(marker, node, pos){
      node.className = "list-entry-highlight";
      /*if(!map.getBounds().contains(marker.point)){
        map.panTo(marker.point);
      }*/
//      autoScroll(node);
    }
    function unhighlightPos(marker, node, pos){
      node.className = "list-entry";
    }
    function openWInfoWindow(data){
      var title = data.city + "天气情况";
      var htmlcur = '<div style="width:400px">' + data.info;
      var search = 'http://www.google.cn/search?hl=zh-CN&q=' + data.city + ' + 天气';
      var search2 = 'http://news.google.cn/news?hl=zh-CN&q=' + data.city + ' + 天气';
      htmlcur += '<div style="text-align:right;font-size:12px;"><a href="' + search + '" target="_blank">详情</a> <a href="' + search2 + '" target="_blank">相关资讯</a></div></div>'
      var latlng = new GLatLng(data.lat, data.lng);
      map.openInfoWindowHtml(latlng, htmlcur);
    }
    function openInfoWindow(marker, pos){
      var rs = "";
      var titleHTML = "<a style='margin:0;font-size:15px;font-weight:bold;margin-right:10px;' target='_blank' href='http://www.google.cn/search?q=" + pos["label"] + "'>"+pos["label"]+"</a>";
      if(pos.cata == "ROAD") {
        var re = /^(.*)(省|自治区)/;
        rs = re.exec(pos.region);
        if(rs == null) {
          re = /^(.*)市/;
          rs = re.exec(pos.region);
        }
        rs = rs[0];
        titleHTML = "<h3 style='margin:0;font-size:15px;font-weight:bold;margin-right:10px;'>"+pos["label"]+"</h3>";
      }
      else if(pos.cata == "TRAIN") {
        rs = pos["region"];
      } else {
        rs = pos["label"];
      }
      var html = "<div style='width:300px'>" + titleHTML + "<div style='margin-top:10px;font-size:13px;'>"+pos["info"]+"<div style='margin-top:10px;'>信息来源：<a href='"+pos["source"]["url"]+"' target='blank_'>"+pos["source"]["label"]+"</a></div></div></div>";
      if(typeof searchResult[rs] != "undefined" && searchResult[rs] != null) {
        var tabtitle = "路况信息";
        if(pos["cata"] == "ALARM"){
          tabtitle = "灾害警报";
        }
        if(pos["cata"] == "TRAIN") {
          tabtitle = "临客信息";
        }
        var tab1 = new GInfoWindowTab(tabtitle, html);
        /*searchResult[res][0].html.style.width = "270px";
        searchResult[res][0].html.style.fontSize = "13px";*/
        var html = document.createElement("div");
        html.style.cssText = "width:300px;font-size:13px;";
        var str = "";
        for(var i = 0; i < searchResult[rs][0].length; i++) {
          var news = searchResult[rs][0][i];
          var title = news.titleNoFormatting;
          var pub = news.publisher;
          var pubtime = news.publishedDate;
          var date = new Date(pubtime);
          date = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 ";
          var url = news.unescapedUrl;
          var tit = title;
          if(tit.length > 18) {
            tit = tit.substr(0, 18) + "...";
          }
          str += "<a target='_blank' title=\"" + title + "\" href=\"" + url + "\">" + tit + "</a><br/>";
          str += "<p style='color:#6F6F6F'>" + pub + " " + date + "</p>";
        }
        str += "<a href=\"" + searchResult[rs][1] + "\" target=\"_blank\" style='float:right;padding-top:5px;'>更多新闻</a>";
        html.innerHTML = str;
        var tab2 = new GInfoWindowTab("相关新闻", html);
        marker.openInfoWindowTabs([tab1, tab2]);
      }
      else {
        marker.openInfoWindowHtml(html);
      }
      
      
    }

    function setSearchResult(ele) {
      if(searchNews.results == null || searchNews.results.length == 0 || searchNews.gwsUrl == null){
        searchResult[ele] == null;
      }
      else {
        searchResult[ele] = [searchNews.results, searchNews.gwsUrl];
      }
      if(searchStack.length != 0) {
        var searchEle = searchStack.shift();
        searchNews.setNoHtmlGeneration();
        searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
        if(searchEle[1] == "ROAD") {
          searchNews.execute(searchEle[0] + " 春运");
        } else if(searchEle[1] == "TRAIN") {
          searchNews.execute(searchEle[0] + " 临客");
        }
        else {
          searchNews.execute(searchEle[0]);
        }
      }
    }
    function geocodeWCallback(node, name, iconurl){
      return function(response){
        if (response && response.Placemark && response.Status.code == 200) {
          place = response.Placemark[0];
          var latlng = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
          var marker = addWMarker(latlng, iconurl);
          node.city.lat = place.Point.coordinates[1];
          node.city.lng = place.Point.coordinates[0];
          addWListener(marker, node);
          //TODO add response to Server
          rpcProxy.setWGeo(name, place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
        } else {
          //TODO remove node?
          node.style.textDecoration = "line-through";
        }

        if(geostack.length == 0) {
          resizeMap();
          return;
        }
        var geostackele = geostack.shift();
        geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
      }
    }
    function geocodeCallback(node, name){
      return function(response){
        if (response && response.Placemark && response.Status.code == 200) {
          place = response.Placemark[0];
          node.pos.latlng = [place.Point.coordinates[1], place.Point.coordinates[0]];
          var marker = addMarker(node.pos, node.iconurl);
          addListener(node, marker);
          
          //TODO add response to Server
          rpcProxy.setGeo(name, place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
        } else {
          //TODO remove node?
          node.style.textDecoration = "line-through";
        }

        if(geostack.length == 0) {
          resizeMap();
          return;
        }
        var geostackele = geostack.shift();
        geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
      }
    }
    function dateChange(date) {
      if(typeof date != "undefined") {
        var month = date.getMonth() + 1;
        if(month < 10) {
          month = "0" + month;
        }
        var dat = date.getDate();
        if(dat < 10) {
          dat = "0" + dat;
        }
        if(cur.date == "" + date.getFullYear() + month + dat) return;
        $("datetxt").innerHTML = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
        cur.date = "" + date.getFullYear() + month + dat;
      }
      else {
        if(cur.date == null) return;
        cur.date = null;
        $("datetxt").innerHTML = "全部";
      }
      
      cur.page = 0;
      
      
      rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
      
    }
    
    function onAfterChange() {
      if(cur.date == null) return;
      cur.page = 0;
      searchStack = [];
      searchResult = [];
      if($("category").value == "0") {
        cur.category = "ROAD";
      } else if($("category").value == "3") {
        cur.category = "TRAIN";
      } else {
        cur.category = "ALARM";
      }
      rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
    }
    
    function onOptionsChange(){
      //cur.region = dom.region.options[dom.region.selectedIndex].value;
      //cur.category = dom.category.options[dom.category.selectedIndex].value;
      //cur.date = dom.date.options[dom.date.selectedIndex].value;
      cur.page = 0;
      cur.date = null;
      cur.region = null;
      searchStack = [];
      searchResult = [];
      $("regionsbut").innerHTML = "全部";
      $("regionbutall").style.display = "none";
      $("datetxt").innerHTML = "全部";
      if($("regionslist").style.display != "none") {
        var lh = parsePX($("listContainer").style.height);
        $("listContainer").style.height = (lh + 117) + "px";
      }
      $("regionslist").style.display = "none";
      if($("category").value == "1") {
        rpcProxy.getWeather(0, cur.region);
        $("datediv").style.display = "none";
      }
      else {
        if($("category").value == "0") {
          cur.category = "ROAD";
        }
        else if($("category").value == "2"){
          cur.category = "ALARM";
        } 
        else if ($("category").value == "3") {
          cur.category = "TRAIN"
        }
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
        $("datediv").style.display = "";
      }
    }
    function onPageChange(isWeather){
      return function() {
        searchStack = [];
        searchResult = [];
        cur.page = this.id.substr(1);
        if(isWeather){
          rpcProxy.getWeather(cur.page, cur.region);
        }
        else {
          rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
        }
      }
    }
    $("prePage").onclick = function(){
      if(cur.page == 0) return;
      cur.page--;
      if($("category").value == "1") {
        rpcProxy.getWeather(cur.page, cur.region);
      }
      else {
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
      }
    }
    $("nextPage").onclick = function(){
      if(cur.page == totalPage - 1) return;
      cur.page++;
      if($("category").value == "1") {
        rpcProxy.getWeather(cur.page, cur.region);
      }
      else {
        rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
      }
    }
    var setSearchWe = function() {
      var abc = 1;
    };
    var initAjaxSearch = function() {
      searchNews = new google.search.NewsSearch();
      searchNews.setRestriction(google.search.Search.RESTRICT_EXTENDED_ARGS, { "ned" : "cn"});

      if(searchStack.length != 0) {
        searchEle = searchStack.shift();
        searchNews.setNoHtmlGeneration();
        searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
        if(searchEle[1] == "ROAD") {
          searchNews.execute(searchEle[0] + " 春运");
        }
        else if(searchEle[1] == "TRAIN") {
          searchNews.execute(searchEle[0] + " 临客");
        }
        else {
          searchNews.execute(searchEle[0]);
        }
      }
    };
    return {
      init : function(){
        $("regionslist").style.height = "100px";
        $("regionslist").style.overflow = "auto";
        var wh = window.innerHeight;
        if(!wh) {
          wh = document.body.parentNode.clientHeight;
        }
        wh -= 22;
        $("mapDiv").style.height = wh + "px";
        wh = wh - 130 + "px";
        $("listContainer").style.height = wh;
        map = new GMap2($("mapDiv")); 
        map.setCenter(new GLatLng(33.9434726, 103.0727471), 5);
        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        rpcProxy.getOptions();
        makeShareButton();
        google.load("search", "1.0", {'language': 'zh_CN'});
	      google.setOnLoadCallback(initAjaxSearch, true);
      },
      importWeather: function(data){
        var result = data.result;
        cached.points = [];
        map.clearOverlays();
        dom.container.innerHTML = "";
        for(var i = 0; i < result.length; i++) {
          var city = result[i];
          //if(result[i].current.length == 0 || result[i].forecast.length == 0) continue;
          var title = city.city + "天气情况";
          
          var curcon = city.condition;
          var iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/qing.png';
          if(curcon.indexOf('雨') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/xiaoyu.png';
          }
          else if(curcon.indexOf('云') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/duoyun.png';
          }
          else if(curcon.indexOf('雪') != -1){
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/xiaoxue.png';
          }
          else if(curcon.indexOf("阴") != -1) {
            iconurl = 'http://ditu.google.com/intl/zh-CN_cn/images/yin.png';
          }
          var node = addWNode(title, iconurl);
          node.city = city;
          if(city.lat != null && city.lng != null){
            var marker = addWMarker(new GLatLng(city.lat, city.lng), iconurl);
            addWListener(marker, node);
          } else {
            geostack.push([city.city, node]);
          }        
        }
        if(geostack.length != 0){
          var geostackele = geostack.shift();
          geocoder.getLocations(geostackele[0], geocodeWCallback(geostackele[1], geostackele[0], iconurl));
        }
        else {
          if(result.length != 0) {
            resizeMap();
          }
        }
        if(result.length != 0) {
          totalPage = data.total;
          $("prePage").style.display = "";
          $("nextPage").style.display = "";
          dom.page.style.display = "";
          dom.page.innerHTML = "";
          for(var i = 0; i < totalPage; i++){
            var pageLink = $n("span", "page-link", dom.page, {id:"p"+i});
            pageLink.innerHTML = i+1;
            pageLink.onclick = onPageChange(true);
            dom.page.appendChild(pageLink);
            if(i == data.page){
              pageLink.className = "active-page";
            }
          }
        }
        else {
          $("listContainer").innerHTML = "<div style='margin-top:15px;text-align:center;display:block;*display:inline-block;'>没有查询到相关信息。</div>";
          $("prePage").style.display = "none";
          $("nextPage").style.display = "none";
          dom.page.style.display = "none";
        }
      },
      importResult : function(result){
        map.clearOverlays();
        cached.points = [];
        dom.container.innerHTML = "";
        var data = result.result;
        var cata = result.cata;
        searchResult = [];
        for (var i = 0, pos; pos = data[i]; i++) {
          var node = addNode(pos);
          node.pos = pos;
          pos["cata"] = cata;
          pos.latlng = pos.latlng || cached.latlng[pos.region];
          var re = /^(.*)(省|自治区)/;
          var res = re.exec(pos.region);
          if(res == null) {
            re = /^(.*)市/;
            res = re.exec(pos.region);
            if (res == null) {
              res = [pos.region]
            }
          }
          res = res[0];
          if(typeof searchResult[res] == "undefined") {
            if((cata == "ROAD") || (cata =="TRAIN")){
              searchStack.push([res, cata]);
            }
            else {
              searchStack.push([pos['label'], cata]);
            }
          }
          var iconurl = "";
          if(cata == "ROAD") {
            iconurl = "http://ditu.google.cn/intl/zh-CN_cn/images/truck-disabled.png"
          }
          else if (cata == "TRAIN"){
            iconurl = "http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/rail.png";
          }
          else {
            var label = data[i]["label"];
            iconurl = "/html/blue.png";
            if(label.indexOf("黄色") != -1) {
              iconurl = "http://ditu.google.com/intl/zh-CN_cn/images/yellow.png";
            }
            else if(label.indexOf("橙色") != -1) {
              iconurl = "http://ditu.google.com/intl/zh-CN_cn/images/orange.png";
            }
            else if(label.indexOf("红色") != -1) {
              iconurl = "http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/caution.png";
            }
          }
          if(pos.latlng){
            var marker = addMarker(pos, iconurl);
            addListener(node, marker);
          } else {
            node.iconurl = iconurl
            geostack.push([pos.region, node]);
            
          }
        }
        if(geostack.length != 0){
          var geostackele = geostack.shift();
          geocoder.getLocations(geostackele[0], geocodeCallback(geostackele[1], geostackele[0]));
        }
        else {
          if(data.length != 0) {
            resizeMap();
          }
        }
        if(searchStack.length != 0 && searchNews != null) {
          var searchEle = searchStack.shift();
          searchNews.setNoHtmlGeneration();
          searchNews.setSearchCompleteCallback(this, setSearchResult, [searchEle[0]]);
          if(searchEle[1] == "ROAD") {
            searchNews.execute(searchEle[0] + " 春运");
          }
          else if(searchEle[1] == "TRAIN") {
            searchNews.execute(searchEle[0] + " 临客");
          } else {
            searchNews.execute(searchEle[0]);
          }
        }
        if(data.length != 0) {
          totalPage = result.total;
          $("prePage").style.display = "";
          $("nextPage").style.display = "";
          dom.page.style.display = "";
          dom.page.innerHTML = "";
          for(var i = 0; i < totalPage; i++){
            var pageLink = $n("span", "page-link", dom.page, {id:"p"+i});
            pageLink.innerHTML = i+1;
            pageLink.onclick = onPageChange();
            dom.page.appendChild(pageLink);
            if(i == result.page){
              pageLink.className = "active-page";
            }
          }
        }
        else {
          $("listContainer").innerHTML = "<div style='margin-top:15px;text-align:center;display:block;*display:inline-block;'>没有查询到相关信息。</div>";
          $("prePage").style.display = "none";
          $("nextPage").style.display = "none";
          dom.page.style.display = "none";
        }
      },
      initOptions : function(options){
/*        cached.region = options.region;
        cached.category = options.category;
        //region
        dom.region.removeChild(dom.region.firstChild);
        for (var i in cached.region) {
          var option = new Option(cached.region[i].name, cached.region[i].id);
          dom.region.options[dom.region.options.length] = option;
          
        }
        dom.region.onchange = onOptionsChange;
        //category
        dom.category.removeChild(dom.category.firstChild);
        for(var i in cached.category){
          var option = new Option(cached.category[i].name, cached.category[i].id);
          dom.category.options[dom.category.options.length] = option;
        }
        dom.category.onchange = onOptionsChange;
        //date
        dom.date.removeChild(dom.date.firstChild);
        var now = new Date();
        var month = now.getMonth();
        var year = now.getFullYear();
        var day = now.getDate();
        for (var i = day; i > 0; i--) {
          var label = new Date(year, month, i).toLocaleDateString();
          var d = i < 10 ? "0" + i : i;
          var option = new Option(label, year + "0" + (month + 1) + "" + d);
          dom.date.options[dom.date.options.length] = option;
        }
        if (month > 0) {
          month--;
          for (var i = 31; i > 0; i--) {
            var label = new Date(year, month, i).toLocaleDateString();
            var d = i < 10 ? "0" + i : i;
            var option = new Option(label, year + "0" + (month + 1) + "" + d);
            dom.date.options[dom.date.options.length] = option;
          }
        }
        dom.date.onchange = onOptionsChange;*/
        regions[1] = options.wearegion;
        cur.category = "TRAIN";
        regions[0] = options.roadregion;
        regions[2] = options.alarmregion;
        regions[3] = options.trainregion;

        $("category").value = "3";
        $("category").onchange = onOptionsChange;
        $("viewafter").onclick = onAfterChange;
        new Calendar_("POPUP", "datebut", dateChange, {
          'align': 'left'
        });
        $("regionbutall").onclick = function() {
          this.style.display = "none";
          if($("regionslist").style.display != "none") {
            var lh = parsePX($("listContainer").style.height);
            $("listContainer").style.height = (lh + 117) + "px";
          }
          $("regionslist").style.display = "none";
          if($("regionsbut").innerHTML == this.innerHTML) return;
          cur.region = null;
          cur.page = 0;
          if($("category").value == "1") {
            rpcProxy.getWeather(cur.page, cur.region);
          }
          else {
            rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
          }
          $("regionsbut").innerHTML = this.innerHTML;
        };
        $("regionsbut").onclick = function() {
          var list = $("regionslist");
          if(list.style.display != "none") {
            list.style.display = "none";
            var lh = parsePX($("listContainer").style.height);
            $("listContainer").style.height = (lh + 117) + "px";
            return;
          }
          var lh = parsePX($("listContainer").style.height);
          $("listContainer").style.height = (lh - 117) + "px";
          var reg = null;
          if($("category").value == "0") {
            reg = regions[0];
          }
          else if($("category").value == "1") {
            reg = regions[1];
          }
          else {  
            if($("category").value == "2") {
              reg = regions[2];
            } else {
              reg = regions[3];
            }
          }
          var caps = [];
          for(var i = 0; i < reg.length; i++) {
            var cap = getCapital(reg[i]);
            if(cap == null) {
              continue;
            }
            var isFound = false;
            for(var j = 0; j < caps.length; j++) {
              if(caps[j] == cap) {
                isFound = true;
                break;
              }
            }
            if(!isFound) {
              caps.push(cap);
            }
          }
          for(var i = 0; i < caps.length; i++) {
            for(var j = i; j < caps.length; j++) {
              if(caps[i] > caps[j]) {
                var tmp = caps[i];
                caps[i] = caps[j];
                caps[j] = tmp;
              }
            }
          }
          var butblock = $n("div");
          
          var quanbu = $n("div");
          quanbu.innerHTML = "全部";
          quanbu.style.cssText = 'margin:2px;cursor:pointer;display:inline;float:left;text-decoration:underline;';
          list.innerHTML = "";
          list.appendChild(butblock);
          butblock.appendChild(quanbu);
          var regionList = $n("div");
          quanbu.onclick = function() {
            
            regionList.innerHTML = "";
            for(var i = 0; i < reg.length; i++) {
              var item = $n("div");
              item.innerHTML = reg[i];
              item.style.cssText = 'margin:2px 5px;cursor:pointer;float:left;display:inline;white-space:nowrap;';
              item.onclick = function() {
                $("regionbutall").style.display = "";
                if($("regionslist").style.display != "none") {
                  var lh = parsePX($("listContainer").style.height);
                  $("listContainer").style.height = (lh + 117) + "px";
                }
                $("regionslist").style.display = "none";
                if($("regionsbut").innerHTML == this.innerHTML) return;
                cur.region = this.innerHTML;
                cur.page = 0;
                $("regionsbut").innerHTML = this.innerHTML;
                if($("category").value == "1") {
                  rpcProxy.getWeather(cur.page, cur.region);
                }
                else {
                  rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
                }
              }
              regionList.appendChild(item);
            }
            var clr = $n("div");
            clr.style.cssText = "clear:both;line-height:0;height:0;font-size:0";
            regionList.appendChild(clr);
          }
          
          for(var j = 0; j < caps.length; j++) {
            var cap = $n("div");
            cap.style.cssText = "margin:2px;cursor:pointer;display:inline;float:left;text-decoration:underline;";
            cap.innerHTML = caps[j];
            cap.onclick = function() {
              regionList.innerHTML = "";
              for(var i = 0; i < reg.length; i++) {
                if(getCapital(reg[i]) == this.innerHTML) {
                  var item = $n("div");
                  item.innerHTML = reg[i];
                  item.style.cssText = 'margin:2px 5px;cursor:pointer;float:left;display:inline;white-space:nowrap;';
                  item.onclick = function() {
                    $("regionbutall").style.display = "";
                    if($("regionslist").style.display != "none") {
                      var lh = parsePX($("listContainer").style.height);
                      $("listContainer").style.height = (lh + 117) + "px";
                    }
                    $("regionslist").style.display = "none";
                    if($("regionsbut").innerHTML == this.innerHTML) return;
                    cur.region = this.innerHTML;
                    cur.page = 0;
                    $("regionsbut").innerHTML = this.innerHTML;
                    if($("category").value == "1") {
                      rpcProxy.getWeather(cur.page, cur.region);
                    }
                    else {
                      rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
                    }
                  }
                  regionList.appendChild(item);
                  
                }
                
              }
              var clr = $n("div");
              clr.style.cssText = "clear:both;line-height:0;height:0;font-size:0";
              regionList.appendChild(clr);
            }
            butblock.appendChild(cap);
            
          }
          var clr = $n("div");
          clr.style.cssText = "clear:both;line-height:0;height:0;font-size:0";
          butblock.appendChild(clr);
          list.appendChild(regionList);
          for(var i = 0; i < reg.length; i++) {
            var item = $n("div");
            item.innerHTML = reg[i];
            item.style.cssText = 'margin:2px 5px;cursor:pointer;float:left;display:inline;white-space:nowrap;';
            item.onclick = function() {
              $("regionbutall").style.display = "";
              if($("regionslist").style.display != "none") {
                var lh = parsePX($("listContainer").style.height);
                $("listContainer").style.height = (lh + 117) + "px";
              }
              $("regionslist").style.display = "none";
              if($("regionsbut").innerHTML == this.innerHTML) return;
              cur.region = this.innerHTML;
              cur.page = 0;
              $("regionsbut").innerHTML = this.innerHTML;
              if($("category").value == "1") {
                rpcProxy.getWeather(cur.page, cur.region);
              }
              else {
                rpcProxy.getSearch(cur.region, cur.category, cur.date, cur.page);
              }
            }
            regionList.appendChild(item);
          }
          var clr = $n("div");
          clr.style.cssText = "clear:both;line-height:0;height:0;font-size:0";
          regionList.appendChild(clr);
          list.style.display = "";
        };
        onOptionsChange();
      }
    }
  })();
  window['ChunyunMap'] = {
    'init' : mgr.init,
    'callback_options' : rpcProxy.getOptionsCallback,
    'callback_search' : rpcProxy.getSearchCallback,
    'callback_weather': rpcProxy.getWeatherCallback
  }
})();
ChunyunMap.init();









